package com.projectx.action;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.projectx.R;
import com.projectx.action.contact.DeleteContact;
import com.projectx.action.contact.FindPerson;
import com.projectx.action.contact.Findfriend;
import com.projectx.action.contact.Searchfriend;
import com.projectx.action.contact.TabFragment;
import com.projectx.action.chat.DevoteActivity.AddDevoteActivity;
import com.projectx.action.chat.DevoteActivity.DevoteActivity;
import com.projectx.action.chat.GroupAnnocement.GroupDialogActivity;
import com.projectx.action.chat.GroupChatActivity;
import com.projectx.action.login.LoginActivity;
import com.projectx.action.login.LoginActivity2;
import com.projectx.action.register.Register1;
import com.projectx.action.talk.TalkListActivity;
import com.projectx.entity.User;
import com.projectx.entity.UserData;
import com.projectx.util.ActivityManage;
import com.projectx.util.PermissionUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LitePal.initialize(this);
        setContentView(R.layout.activity_main);
        SQLiteDatabase db = LitePal.getDatabase();
        ActivityManage.clear();
        ActivityManage.addActivity("MainActivity",this);
        File file = new File(Environment
                .getExternalStorageDirectory().toString()
                + "/ProjectX/");
        if (!file.exists()){
            file.mkdir();
        }
        List<UserData> userDataList = LitePal.where("login = ?","1").find(UserData.class);
        if (userDataList.size() > 0){
            final UserData userData = userDataList.get(0);
            FutureTask<JSONObject> task = new FutureTask<>(new Callable<JSONObject>() {
                @Override
                public JSONObject call() throws Exception {
                    JSONObject getMessage = null;
                    try {
                        Socket socket = new Socket("106.15.192.117", 2333);
                        Gson gson = new Gson();
                        User user = new User();
                        user.setFlag(1);
                        user.setUserName(userData.getUsername());
                        user.setPassword(userData.getPassword());
                        String message = gson.toJson(user);
                        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                        dataOutputStream.writeUTF(message);
                        dataOutputStream.flush();
                        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                        String netStr = dataInputStream.readUTF();
                        try {
                            getMessage = new JSONObject(netStr);
                        } catch (JSONException e) {
                            Log.d("kmh", "doInBackground: 后端JSON字符串有问题祭天吧");
                        } finally {
                            dataInputStream.close();
                            dataOutputStream.close();
                            socket.close();
                        }

                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    return getMessage;
                }
            });
            Thread thread = new Thread(task);
            thread.start();
            //解析验证JSON字符串返回数据
            try {
                JSONObject message = task.get(5, TimeUnit.SECONDS);
                int code = message.getInt("code");
                if (code == 0) {
                    Intent intent = new Intent(MainActivity.this, TalkListActivity.class);//进入主界面
                    intent.putExtra("accountName", userData.getUsername());
                    intent.putExtra("password",userData.getPassword());
                    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivity(intent);
                    ActivityManage.removeAllActivityExcept("TalkListActivity");
                    finish();
                }
            } catch (TimeoutException te) {
                Toast.makeText(MainActivity.this, "超时错误", Toast.LENGTH_SHORT).show();
            } catch (JSONException je) {
                Toast.makeText(MainActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                je.printStackTrace();
            } catch (Exception ne){
                ne.printStackTrace();
                Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
            }
        }
        final Button login = findViewById(R.id.login);
        final Button talkList = findViewById(R.id.ListTalk);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
        talkList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Register1.class);
                //intent.putExtra("accountName","sky");
                startActivity(intent);
            }
        });
    }

}
